package com.example.onlineproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.onlinecommon.entry.PageUtil;
import com.example.onlinecommon.utils.R;
import com.example.onlineproject.entry.Project;
import com.example.onlineproject.feign.CouponFeignService;
import com.example.onlineproject.mapper.ProjectMapper;
import com.example.onlineproject.service.ProjectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
@Slf4j
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Autowired
    private  ProjectMapper projectMapper;

    @Autowired
    private CouponFeignService couponFeignService;



    /**
     * 批量新增数据  saveBatch()
     * Collection<T> entityList, int batchSize
     */
    public void  insertBatchProject(){
        Collection<Project> entityList = new ArrayList<Project>();
        String projectName = "基本商品";

        for(int i = 0; i <100; i++){
            Project project = new Project();
            project.setProjectName(projectName + i);
            BigDecimal pPrice = new BigDecimal("" + i);
            project.setProjectPrice(pPrice);
            entityList.add(project);
        }
        boolean b = this.saveBatch(entityList);
        log.info("批量插入：" + b);
    }

    /**
     * 查询所有的数据
     * @return
     */
    @GlobalTransactional
    @Transactional
    public PageInfo<Project> selectProjectList(PageUtil pageUtil){
        int pageNo = pageUtil.getPageNo();
        int pageSize = pageUtil.getPageSize();
        PageHelper.startPage(pageNo,pageSize);
//        List<Project> lists = projectMapper.selectProjectList();

        Wrapper<Project> queryWrapper = new QueryWrapper();
        List<Project> lists = projectMapper.selectList(queryWrapper);

        PageInfo<Project> pageInfo = new PageInfo<>(lists);
        return pageInfo;
    }


    /**
     *  根据 id 更新数据
     * @param project
     */
    @GlobalTransactional
    @Transactional
    public void updateProjectById(Project project){
        int i = projectMapper.updateById(project);
        try{
            R r = couponFeignService.testSeata();
        }catch (Exception e){
            log.info("根据 id 更新数据 的异常信息02：" + e.getMessage());
        }

        int num = 1/0;  // 出现异常 看看两个微服务都回滚不
    }

}
